<!DOCTYPE html>
<html>
<head>
    <include file="./Application/Home/View/Tpl/head.html" />
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/libs/dataTables.fixedHeader.css">
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/libs/dataTables.tableTools.css">

    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=kaRXcPncFqA676tqP7vR6MqT4cQqQ0p7"></script>
    <style type="text/css">
        #allmap img {
            max-width: inherit;
        }

    </style>
    <style type="text/css">
        html,body{margin:0;padding:0;}
        .iw_poi_title {color:#CC5522;font-size:14px;font-weight:bold;overflow:hidden;padding-right:13px;white-space:nowrap}
        .iw_poi_content {font:12px arial,sans-serif;overflow:visible;padding-top:4px;white-space:-moz-pre-wrap;word-wrap:break-word}
    </style>
</head>
<body class="fixed-header theme-blue-gradient">
<div  id="theme-wrapper">
    <include file="./Application/Home/View/Tpl/header.html" />
    <div id="page-wrapper" class="container">
        <div class="row">
            <include file="./Application/Home/View/Tpl/menu.html"/>

            <div id="content-wrapper">
                <div class="row">
                    <include file="./Application/Home/View/Tpl/alert.html"/>

                    <div class="col-md-12">
                        <button class="btn  pull-left btn-danger btn-lg" id="clearsta">
                            <i class="fa  fa-trash-o"></i> 清空终端列表
                        </button>
                        <button class="btn pull-right  btn-success btn-lg" action="" id="scanstatus" name="scanstatus">
                            扫描状态读取中... ...
                        </button>
                    </div>
                </div>
                <BR>
                <div class="row">


                    <div class="col-md-12">
                        <div class="main-box clearfix">
                            <div class="table-responsive">
                                <table id="table-example" class="table table-hover"  cellspacing="0" width="100%">
                                    <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>终端MAC地址</th>
                                        <th>厂家</th>
                                        <th>目的/网络地址</th>
                                        <th>请求链接SSID</th>
                                        <!-- <th>设备距离</th>-->
                                        <th>设备名称</th>
                                        <th>信号强度</th>
                                        <th>距离</th>
                                        <th>捕获时间</th>
                                        <th>GPS</th>
                                    </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>

                    </div>
                </div>
                <include file="./Application/Home/View/Tpl/footer.html"/>

            </div>
        </div>
    </div>
</div>

<div class="modal   fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 100%;margin: 0px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">终端详情</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <table id="detailtable" class="table table-hover" style="margin-bottom: 0px"  cellspacing="0" width="100%">
                            <thead>
                            <tr>
                                <th>终端MAC地址</th>
                                <th>目的/网络地址</th>
                                <th>请求链接SSID</th>
                                <th>设备名称</th>
                                <th>信号强度</th>

                                <th>捕获时间</th>
                                <!--<th>距离</th>-->
                                <th>操作</th>

                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td id="smac"></td>
                                <td id="dimac"></td>
                                <td id="requsetssid"></td>
                                <td id="devname"></td>
                                <td id="signalstrength"></td>
                                <td id="timeparse"></td>
                               <!-- <td>
                                    <span class="label label-success" mac="" id="distance" class="distance"></span>
                                </td>-->
                                <td>
                                    <button class="btn btn-primary" id="yazhi">压制</button>

                                    <button class="btn   btn-info distance" id="distance" type="button">
                                        开启定位
                                    </button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>

                    <div id="allmap" style="height:330px;width:100%;"></div>

                    <div id="distance_map" class="col-md-12" style="display: none;padding-top: 20px">

                        <div class="label label-primary macval pull-right">实时定位启动中...</div>
                        <div class="label label-success distanceval pull-right" style="margin-right: 10px"></div>
                        <div id="locationPanel" style="width: 100%;height:400px;"></div>
                        <audio id="snd" src="" autoplay></audio >
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" data-dismiss="modal"  class="btn btn-success btn-lg" >关 闭</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>



<include file="./Application/Home/View/Tpl/commjs.html" />
<!--<script src="__PUBLIC__/js/jquery.dataTables.js"></script>
<script src="__PUBLIC__/js/jquery.dataTables.bootstrap.js"></script>
-->
<script src="__PUBLIC__/datatable/datatables.min.js"></script>
<script src="__PUBLIC__/datatable/dataTables.bootstrap.js"></script>

<link rel="stylesheet" type="text/css" href="__PUBLIC__/datatable/buttons/css/buttons.bootstrap4.min.css">
<script src="__PUBLIC__/datatable/buttons/js/dataTables.buttons.js"></script>
<script src="__PUBLIC__/datatable/buttons/js/jszip.min.js"></script>
<script src="__PUBLIC__/datatable/buttons/js/buttons.html5.min.js"></script>

<script src="__PUBLIC__/js/alertsetting.js"></script>
<!-- highcharts-->
<script src="__PUBLIC__/plugins/highcharts/highcharts.js"></script>

<script type="text/javascript">
    var map = null;
    var newmap = true;
    var base = new Base64();

    var distanceinterval=null;
    $(function() {
        function getmacalert() {
            $.ajax({
                url : "{:U('/Home/scanwifi/getappearmac','',false)}",
                type : "post",
                dataType : "json",
                data: null,
                timeout:6000,
                success:function(result){
                    console.log(result);

                    if(result.status==true){
                        $("#macname").html('');
                        for(var iloop=0; iloop<result.data.length;iloop++){
                            $("#macalert").show();
                            $("#macname").append('<h4 >'+
                                '告警标识：' + result.data[iloop]['alertname'] +
                                ' | mac：' + result.data[iloop]['s_mac']+
                                ' 在' + result.data[iloop]['timedesc'] + '出现！</h4>');
                        }
                    }
                },
                error:function(msg){
                    console.log(msg);
                }
            });
        }
        setInterval(getmacalert, 10000);

        var interval;
        var gpsinterval;
        var currentmac='';
        var firstload=true;
        var  historyPoint= new Array();
        function drawPolyline( bmap, points) {
            if (points==null  || points.length<=1 ) {
                return;
            }

            var line=new BMap.Polyline(points, {
                strokeColor : "blue",
                strokeWeight : 1,
                strokeOpacity : 1
            });
            bmap.addOverlay(line); // 画线
            line.show();
        }
        function setmap(gps) {

            //gps="116.404,39.915  120.245397 31.548585";
            if(map==null){
                console.log('map is null, reload');
                map=new BMap.Map("allmap");
            }else
            {
                if(newmap)
                {
                    historyPoint=[];
                    map.clearOverlays();
                    newmap=false;
                }
            }


            if(gps!=""){
                //map.clearOverlays();
                var lan=gps.split(' ');
                var sContent =
                    "<h4 style='margin:0 0 5px 0;padding:0.2em 0'>设备实时位置</h4>" +
                    "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>经纬度:"+gps+"</p>" ;
                // 百度地图API功能

                //坐标转换完之后的回调函数
                var point = new BMap.Point(lan[1], lan[0]);


                translateCallback = function (data){
                    if(data.status === 0) {
                        if(historyPoint.length>=1 &&
                            historyPoint[historyPoint.length-1].lng==data.points[0].lng
                            && historyPoint[historyPoint.length-1].lat==data.points[0].lat){
                            console.log('location not change');
                            return;
                        }

                        var marker = new BMap.Marker(data.points[0]);
                        var sContent =
                            "<h4 style='margin:0 0 5px 0;padding:0.2em 0'>实时位置</h4>" +
                            "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>经纬度:" + gps + "</p>";
                        var infoWindow = new BMap.InfoWindow(sContent);  // 创建信息窗口对象

                        map.addOverlay(marker);
                        marker.openInfoWindow(infoWindow);
                        if(firstload){
                            map.centerAndZoom(point, 15);
                            map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
                        }
                        firstload=false;
                        historyPoint.push(data.points[0]);
                        drawPolyline(map,historyPoint);

                    }
                }

                var convertor = new BMap.Convertor();
                var pointArr = [];
                pointArr.push(point);
                convertor.translate(pointArr, 1, 5, translateCallback);



            }

        }



        var count = [],time = [];
        var mac='';

        var distancestatus=true;
        $(".distance").click(function(){
            if(distancestatus){
                $("#allmap").hide();
                $("#distance_map").show();



                clearInterval(distanceinterval);
                mac = $(this).attr('mac');
                var ssid = $(this).attr('ssid');
                var dis=$(this);
                $('#snd').attr('src','__PUBLIC__/audio/success.mp3');
                $(this).html('停止定位');
                $('.macval').html('实时定位启动中... ...');
                drawChart( );

                $.ajax({
                    url : "{:U('/Home/scanwifi/getStrength','',false)}",
                    type : "post",
                    dataType : "json",
                    data: {action:"set", mac:mac},
                    timeout:30000,
                    success:function(result){
                    },
                    error:function(msg){
                        console.log(msg);      //执行错误
                    }
                });
                distancestatus=false;
            }else{
                clearInterval(distanceinterval);
                mac = $(this).attr('mac');
                var ssid = $(this).attr('ssid');
                var dis=$(this);
                $(this).html('开启定位');
                //$('.macval').html('实时定位已停止');
                distancestatus=true;
            }
        });

        function drawChart( ){
            Highcharts.setOptions({
                global: {
                    useUTC: false
                }
            });
            function activeLastPointToolip(chart) {
                var points = chart.series[0].points;
                chart.tooltip.refresh(points[points.length -1]);
            }
            var chart = Highcharts.chart('locationPanel', {
                chart: {
                    type: 'spline',
                    marginRight: 10,
                    events: {
                        load: function () {
                            var series = this.series[0],
                                    chart = this;
                            activeLastPointToolip(chart);
                            distanceinterval=setInterval(function () {
                                $.ajax({
                                    url : "{:U('/Home/scanwifi/getStrength','',false)}",
                                    type : "post",
                                    dataType : "json",
                                    data: {action:"get", mac:mac},
                                    timeout:30000,
                                    success:function(result){
                                        console.log(result);
                                        if(result.signalstrength){
                                            var sl=parseInt(result.signalstrength);
                                            var distance=Math.round(Math.pow (10,Math.abs( sl) /(10*4))*10/100);
                                            var strength=result.signalstrength;
                                            if(sl==66){
                                                strength=0;
                                                distance=0;
                                                $('.distanceval').html(' 目标消失');
                                            }else if(distance>30){
                                                distance=30;
                                            }
                                            else{
                                                $('#snd').attr('src','__PUBLIC__/audio/'+distance+'.mp3');
                                                $('.distanceval').html(' 距离：'+distance+'米');
                                            }
                                            $('.macval').html('场强：'+strength);

                                            var x = (new Date()).getTime(), // 当前时间
                                                y = distance;          // 随机值
                                            series.addPoint([x, y], true, false);
                                            activeLastPointToolip(chart);


                                        }
                                    },
                                    error:function(msg){
                                        console.log(msg);      //执行错误
                                    }
                                });


                            }, 5000);
                        }
                    }
                },
                title: {
                    text: ''
                },
                xAxis: {
                    type: 'datetime',
                    tickPixelInterval: 100
                },
                yAxis: {
                    title: {
                        text: null
                    }
                },
                tooltip: {
                    formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                        Highcharts.numberFormat(this.y, 2);
                    }
                },
                legend: {
                    enabled: false
                },
                series: [{
                    name: ' ',
                    data: (function () {
                        // 生成随机值
                        var data = [],
                                time = (new Date()).getTime();
                        data.push({
                            x: time + 1000,
                            y: 0
                        });
                        return data;
                    }())
                }]
            });
        }

        function toUtf8(str) {
            var out, i, len, c;
            out = "";
            len = str.length;
            for(i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                } else if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
                } else {
                    out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
                }
            }
            return out;
        }

        var table = $('#table-example').DataTable({
            "stateSave": true,
            responsive: true,
            "deferRender": true,
            dom: 'Bfrtip',
            "buttons": [
                {
                    'extend': 'excel',
                    'text': '导出excel',
                    'className': 'btn btn-primary',
                    'exportOptions':{
                        format: {
                            body: function ( data, row, column, node ) {
                                // Strip $ from salary column to make it numeric
                                return column === 3?
                                    toUtf8(data):
                                    data;
                            }
                        }
                    }
                }
            ],
            "ajax": {
                "url": "{:U('/Home/Apwifidata/getdata','',false)}",
                "type": "POST"
            },
            /*"columnDefs": [
                {
                    "targets": [9],
                    "visible": false
                }
            ],*/
            "columns": [
                {"data": "id"},
                {"data": "smac"},
                {"data": "vendor"},
                {"data": "dimac"},
                //{ "data": "imac" },
                {"data": "requsetssid",
                    "render":
                        function(data, type, row, meta) {
                            //type 的值  dispaly sort filter
                            //代表，是显示类型的时候判断值的长度是否超过8，如果是则截取
                            //这里只处理了类型是显示的，过滤和排序返回原始数据
                            if(!data){return null;}
                            return base.decode(data);
                        }
                },
                {"data": "devname"},
                {"data": "signalstrength"},
                {"data": "distance"},
                {"data": "timeparse"},
                {"data": "gps"}
            ],
            "oLanguage": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有符合条件的终端",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 个终端",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索终端:",
                "sUrl": "",
                "sEmptyTable": "没有扫描到任何终端信息",
                "sLoadingRecords": "数据加载中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            }
        });

        $('#table-example tbody').on('click', 'tr', function () {
            clearInterval(interval);

            var data = table.row(this).data();
            console.log(data);
            $("#smac").html(data['smac']);
            $("#dimac").html(data['dimac'].replace(/<BR>/, '|'));
            $("#requsetssid").html(base.decode(data['requsetssid']));
            $("#devname").html(data['devname']);
            $("#signalstrength").html(data['signalstrength']);
            //$("#distance").html(data['distance'] + '<span class="glyphicon glyphicon-play"></span>');
            $("#distance").attr('mac', data['smac']);
            $("#timeparse").html(data['timeparse']);

            $("#yazhi").attr('signalPath',data['signalstrength'] );
            $("#yazhi").attr('apmac',data['dimac'].replace(/<BR>/, '|').split('|')[1] );
            $("#yazhi").attr('stamac',data['smac'] );
            $("#yazhi").attr('action','start' );
            //获取当前ap是否正在破解或攻击或伪装
            $.ajax({
                url : "{:U('/Home/scanwifi/getstatus','',false)}",
                type : "post",
                dataType : "json",
                data: {mac:data['smac']},
                timeout:6000,
                success:function(result){
                    console.log(result);
                    if(result.status==true){
                        if(result.data.yazhi!=''){
                            $("#yazhi").attr('action', 'stop');
                            $("#yazhi").html('正在压制中...');
                        }
                    }
                },
                error:function(msg){
                    console.log(msg);
                }
            });

            $("#yazhi").click(function () {
                $btn=$(this);
                var apmac=$(this).attr('apmac');
                var srcmac=$(this).attr('stamac');
                var action=$(this).attr('action');
                var signalPath=-1;
                if(action=='start'){
                    //开始压制
                    $(this).html('压制开启中...');
                }else{
                    //停止压制
                    $(this).html('压制停止中...');
                }
                /* STAAttackAct(action,signalPath,apmac,srcmac) */
                $.ajax({
                    url : "{:U('/Home/Scanwifi/yazhi','',false)}",
                    type : "post",
                    dataType : "json",
                    data: {action:action,signalPath:signalPath, apmac:apmac, srcmac:srcmac},
                    timeout:6000,
                    success:function(result){
                        if(result.status ){
                            if(action=='start'){
                                $btn.html('压制中...');
                                $btn.attr('action','stop');
                            }else{
                                $btn.html('压制');
                                $btn.attr('action','start');
                            }

                        }
                        else{
                            alert('压制开启失败，终端当前没有连接对应的AP。');
                        }
                    },
                    error:function(msg){
                        console.log(msg);      //执行错误

                    }
                });
            });

            $('#myModal').modal('toggle');

            newmap=true;
            setmap(data['gps']);

            currentmac=data['smac'];
            gpsinterval=window.setInterval(getcurrentGPS, 4000);
        });

        $('#myModal').on('hide.bs.modal', function () {
            newmap=true;
            clearInterval(gpsinterval);
            //定位清空
            clearInterval(distanceinterval);
            $("#distance").html('开启定位');
            $('.macval').html(' ');
            $('.distanceval').html(' ');
        });

        function getcurrentGPS() {
            if(currentmac!=''){
                //获取当前mac最新的gps字段信息
                $.ajax({
                    url : "{:U('/Home/apwifidata/getgpsbymac','',false)}",
                    type : "post",
                    dataType : "json",
                    data: {mac:currentmac},
                    timeout:6000,
                    success:function(result){
                        if(result.data && result.data.length>=1 && result.data[0].position!=''){
                            setmap(result.data[0].position);
                        }
                    },
                    error:function(msg){
                        console.log(msg);      //执行错误
                    }

                });

            }
        }

    });


    $('#stopscan').click(function () {
        $.ajax({
            url : "{:U('/Home/scanwifi/stopscan','',false)}",
            type : "post",
            dataType : "json",
            data: null,
            timeout:6000,
            success:function(result){
                if(result.status=="start"){
                    $("#stop").hide();
                    $("#start").show( );
                }

            },
            error:function(msg){
                console.log(msg);      //执行错误
                alert("系统错误!");
            }

        });
    });

    $('#startscan').click(function () {
        $.ajax({
            url : "{:U('/Home/scanwifi/startscan','',false)}",
            type : "post",
            dataType : "json",
            data: null,
            timeout:6000,
            success:function(result){
                console.log(result);
                if(result.status=="stop"){
                    $("#start").hide();
                    $("#stop").show( );

                }
            },
            error:function(msg){
                console.log(msg);      //执行错误
                alert("系统错误!");
            }

        });
    });

    $("#clearsta").click(function(){
        $.ajax({
            url : "{:U('/Home/scanwifi/DatabaseClearSTA','',false)}",
            type : "post",
            dataType : "json",
            data: null,
            timeout:6000,
            success:function(result){
                console.log(result);
                $('#table-example').dataTable().fnClearTable();
            },
            error:function(msg){
                console.log(msg);      //执行错误
                alert("系统错误!");
            }
        });
    });

    $.ajax({
        url : "{:U('/Home/scanwifi/getscanstatus','',false)}",
        type : "post",
        dataType : "json",
        data: null,
        timeout:6000,
        success:function(result){
            if(result.scanstatus=="runing"){
                $("#scanstatus").attr('action','stop');
                $("#scanstatus").html('停止扫描');
                $("#scanstatus").attr('class','btn pull-right  btn-success btn-lg');
            }
            else{
                $("#scanstatus").attr('action','start');
                $("#scanstatus").html('开启扫描');
                $("#scanstatus").attr('class','btn pull-right  btn-primary btn-lg');
            }
        },
        error:function(msg){
            console.log(msg);      //执行错误
            $("#scanstatus").attr('action','start');
            $("#scanstatus").html('扫描组件状态未知');
        }

    });
    $('#scanstatus').click(function () {
        var action=$(this).attr('action');
        $.ajax({
            url : "{:U('/Home/scanwifi/doscan','',false)}",
            type : "post",
            dataType : "json",
            data: {action:action},
            timeout:6000,
            success:function(result){
                if(result.status=="stop"){
                    $("#scanstatus").attr('action','stop');
                    $("#scanstatus").html('停止扫描');
                    $("#scanstatus").attr('class','btn  pull-right btn-success btn-lg');
                }
                else{
                    $("#scanstatus").attr('action','start');
                    $("#scanstatus").html('开启扫描');
                    $("#scanstatus").attr('class','btn pull-right  btn-primary btn-lg');
                }

            },
            error:function(msg){
                console.log(msg);      //执行错误
                $("#scanstatus").attr('action','start');
                $("#scanstatus").html('扫描组件状态未知');
            }

        });
    });



</script>



</body>
</html>


